//
//  OAuthTableController.swift
//  传智小微博
//
//  Created by lxgoodgo on 16/4/18.
//  Copyright © 2016年 liux.orz. All rights reserved.
//

import UIKit
import AFNetworking

let AppKey = "2502178694"
let AppSecret = "16878a5cee575619b31e2302c14f8276"
let Redirect_Uri = "https://www.baidu.com/"
class OAuthTableController: UIViewController {

    override func loadView() {
//        view = webView
//      
////        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)")
//        
//        let url  = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)")
////        ?client_id= \(AppKey)&redirect_uri=\(Redirect_Uri)
//        let request = NSURLRequest(URL: url!)
//        
//        webView.loadRequest(request)
//        
////        App Key：982612257
////        App Secret：16878a5cee575619b31e2302c14f8276
        
        
        
        view = webView
        webView.delegate = self
        // 定义一个url
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        // 定义一个request
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)

//
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    func setupNav()
    {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消登录", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
        
    }
    
    //懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    @objc private func cancle()
    {
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    @objc private func auto()
    {
        print("自动填充了")
        let jsString = "document.getElementById('userId').value='\(CZWeiboName)';document.getElementById('passwd').value='\(CZWeiboPasswd)'"
        // JS注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)

    }
}

extension OAuthTableController : UIWebViewDelegate
{
    func webViewDidStartLoad(webView: UIWebView) {
        //SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //SVProgressHUD.dismiss()
    }
    
    //
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断urlstring 是否有值 前缀是否是我们的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_URI)
        {
            //判断请求参数是否存在
            if let q = request.URL?.query
            {
                //获取code 获取请求授权返回的code
                let code = q.substringFromIndex("index=".endIndex)
                print("终于等到你 还好没放弃 code:\(code)")
            }
        }
        
        return true
    }
    
    
    
}
//分类
extension OAuthTableController
{
    //用 请求授权返回的 code， 来 获取授权  ，来得到access_token:用户授权的唯一票据，用于调用微博的开放接口，同时也是第三方应用验证微博用户登录的唯一票据，第三方应用应该用该票据和自己应用内的用户建立唯一影射关系，来识别登录状态，不能使用本返回值里的UID字段来做登录识别。
    func loadUserAccount(code: String)
    {
        //根据用户userId  获取 用户信息
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id" : APPKEY,
            "client_secret" : APPSECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : REDIRECT_URI
            
//            client_id	true	string	申请应用时分配的AppKey。
//            client_secret	true	string	申请应用时分配的AppSecret。
//            grant_type	true	string	请求的类型，填写authorization_code
//            
//            grant_type为authorization_code时
//            必选	类型及范围	说明
//            code	true	string	调用authorize获得的code值。
//            redirect_uri
            
        ]
        
        //利用 封装好的 网络请求 单例类
        CZNetworkTools.sharedTools.request(CZRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil
            {
                return
            }
            
            //判断可选值
            guard let dataDict = response as? [String : AnyObject]  else
            {
                print("返回的不是一个字典 ")
                return
                
            }
            //获取用户请求 得到的数据
            let userAccount = UserAccount.init(dict: dataDict)
            
            self.getUserInfo(userAccount)
            
        }

    }
    
    func getUserInfo(useraccount : UserAccount)
    {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = [
            "access_token":useraccount.access_token!,
            "uid" : useraccount.uid!
        ]
        
        CZNetworkTools.sharedTools.request(CZRequestMethod.GET, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil
            {
                print("请求失败")
                return
            }
            
            guard let responseData = response as? [String: AnyObject] else
            {
                print("返回的数据不是一个字典")
                return
            }
            useraccount.avatar_large = responseData["avatar_large"] as? String
            useraccount.screen_name = responseData["screen_name"] as? String
            //对用户数据进行保存
            
            
    }
    
    
}



